package controller;

import gui.ConsolePanel;
import gui.TextEditorPanel;
import jahuwaldt.plot.Plot;

import java.io.File;

import javax.swing.JFileChooser;

public class FileController {
	public static FileController getInstance() {
		if (fileController == null) {
			fileController = new FileController();
			chooser = new JFileChooser(new File("/"));
			chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
				public boolean accept(File f) {
					if (f.getName().endsWith(".db") || f.isDirectory()) {
						return true;
					}
					return false;
				}

				public String getDescription() {
					return ".db";
				}
			});
			return fileController;
		} else {
			return fileController;
		}
	}

	public void newFile() {
		this.textEditorPanel.addInternalFrame();
	}
	
	public void newPlot(){
		this.textEditorPanel.addInternalPlotFrame(null);
	}

	public void openFile() {
		String read = "";
		String fileContent = "";
		int state = chooser.showOpenDialog(null);
		File file = chooser.getSelectedFile();
		if (file != null && state == JFileChooser.APPROVE_OPTION) {
			this.textEditorPanel.addInternalDBBrowserFrame(file);
			
		}
	}

	public void saveFile() {
		if (this.textEditorPanel.getSelectedPane() == null) {
			this.consolePanel.appendText("No File Open or Edited!\n");
			return;
		} else if (this.textEditorPanel.getSelectedPane().getFile() == null)
			saveAsFile();
		else
			this.textEditorPanel.getSelectedPane().saveFile();
	}

	public void saveAsFile() {
		if (this.textEditorPanel.getSelectedPane() == null) {
			this.consolePanel.appendText("No File Open or Edited!\n");
			return;
		}
		File saveFile = null;
		int state = chooser.showSaveDialog(null);
		int desIdx = 0;
		if (chooser.getSelectedFile() != null
				&& state == JFileChooser.APPROVE_OPTION) {
			desIdx = chooser.getSelectedFile().getName().indexOf(".java");

			if (desIdx < 0) {
				String filepath = chooser.getSelectedFile().getPath();
				String filename = chooser.getSelectedFile().getName() + ".java";
				int nindex1 = filepath.lastIndexOf("\\");
				filepath = filepath.substring(0, nindex1 + 1);
				saveFile = new File(filepath + filename);

			} else {
				saveFile = chooser.getSelectedFile();
			}
			this.textEditorPanel.getSelectedPane().saveAs(saveFile);
		}
	}

	public void setTextEditorPanel(TextEditorPanel textEditorPanel) {
		this.textEditorPanel = textEditorPanel;
	}

	public void setConsolePanel(ConsolePanel consolePanel) {
		this.consolePanel = consolePanel;
	}

	public void setCurPlotData(Plot curPlotData) {
		this.curPlotData = curPlotData;
	}

	public Plot getCurPlotData() {
		return curPlotData;
	}

	private static FileController fileController = null;
	private TextEditorPanel textEditorPanel = null;
	private ConsolePanel consolePanel = null;
	private static JFileChooser chooser = null;
	private Plot curPlotData = null;
}
